package org.chinasoft.service.impl;

import org.chinasoft.dao.MenuMapper;
import org.chinasoft.dao.RoleMenuMapper;
import org.chinasoft.entity.Menu;
import org.chinasoft.service.MenuService;
import org.chinasoft.vo.MenuTreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public List<Menu> getAll() {
        return menuMapper.getAll();
    }

    @Override
    public Set<Menu> getByRoleId(Long roleId) {
        return roleMenuMapper.getMenuSetByRoleId(roleId);
    }

    @Override
    public List<MenuTreeNode> buildTreeByAllMenuList(List<Menu> menuList) {
        List<MenuTreeNode> menuTreeNodeList = new ArrayList<>();

        List<Menu> parentMenuList = menuList.stream()
                .filter(menu -> menu.getParentId() == 0)
                .collect(Collectors.toList());

        List<Menu> subMenuList = menuList.stream()
                .filter(menu -> menu.getParentId() != 0)
                .collect(Collectors.toList());

        for (Menu parentMenu : parentMenuList) {
            MenuTreeNode menuTreeNode = new MenuTreeNode();
            menuTreeNode.setMenu(parentMenu);

            List<Menu> childList = new ArrayList<>();
            for (Menu subMenu : subMenuList) {
                if (subMenu.getParentId().equals(parentMenu.getMenuId())) {
                    childList.add(subMenu);
                }
            }
            menuTreeNode.setChildList(childList);
            menuTreeNodeList.add(menuTreeNode);
        }
        return menuTreeNodeList;
    }
}
